<script lang="jsx" setup>
import { computed, nextTick, ref } from 'vue';
import { Button } from 'ant-design-vue';
import dayjs from 'dayjs';
import Table from '@/components/common/table.vue';
import CommonSearch from '@/components/common/common-search.vue';
import Modal from '@/components/common/modal.vue';
import {
  addThroughHoleFrame,
  deleteThroughHoleFrame,
  exportThroughHoleFrame,
  scrapThroughHoleFrame,
  updateThroughHoleFrame
} from '@/service/api/modules/workwear/through-hole-frame-management';
import Add from './modules/add.vue';

const commonSearchRef = ref(null);
const tableRef = ref(null);
const searchParams = ref({
  model: null,
  states: null,
  time: null
});

const searchFormList = [
  {
    type: 'input',
    key: 'model',
    label: '型号',
    placeholder: '请输入型号',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 6
  },
  {
    type: 'select',
    key: 'states',
    label: '状态',
    placeholder: '请选择状态',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 6,
    selectOptions: [
      {
        value: '1',
        label: '生效'
      },
      {
        value: '2',
        label: '报废'
      }
    ]
  },
  {
    type: 'dateRangePicker',
    key: 'time',
    label: '日期',
    span: 24,
    md: 12,
    lg: 10,
    xl: 8,
    xxl: 6
  }
];

const searchData = computed(() => {
  const params = {
    ...searchParams.value
  };
  if (searchParams.value?.[0]) {
    params.startTime = dayjs(searchParams.value.time[0]).format('YYYY-MM-DD');
    params.endTime = dayjs(searchParams.value.time[1]).format('YYYY-MM-DD');
  }
  delete params.time;
  return params;
});

const column = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'model',
    dataIndex: 'model',
    title: '型号',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 150
  },
  {
    key: 'applicationtime',
    dataIndex: 'applicationtime',
    title: '申请时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 180
  },
  {
    key: 'statesName',
    dataIndex: 'statesName',
    title: '状态',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'applicant',
    dataIndex: 'applicant',
    title: '申请人',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 130
  },

  {
    key: 'position',
    dataIndex: 'position',
    title: '存放位置',
    align: 'center',
    checked: true,
    ellipsis: true
  },

  {
    key: 'scrapper',
    dataIndex: 'scrapper',
    title: '报废人',
    align: 'center',
    checked: true,
    ellipsis: true
  },

  {
    key: 'reasonforscrapping',
    dataIndex: 'reasonforscrapping',
    title: '报废原因',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'scraptime',
    dataIndex: 'scraptime',
    title: '报废时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 160
    // customRender: ({ record }) => {
    //   return dayjs(record.upkeepEndTime).format('YYYY-MM-DD HH:mm:ss');
    // }
  },

  {
    key: 'notes',
    dataIndex: 'notes',
    title: '备注',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'table-cz',
    dataIndex: 'table-cz',
    title: '操作',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 140,
    fixed: 'right',
    customRender: ({ record }) => {
      return (
        <div>
          <Button
            type="link"
            danger
            class="pl-3px pr-3px"
            onClick={() => {
              del(record);
            }}
          >
            删除
          </Button>
          <Button
            type="link"
            class="pl-3px pr-3px"
            onClick={() => {
              handleOpen(record);
            }}
          >
            修改
          </Button>
          {Number(record.states) === 1 ? (
            <Button type="link" class="pl-3px pr-3px" onClick={() => handleScrapOpen(record)}>
              报废
            </Button>
          ) : (
            ''
          )}
        </div>
      );
    }
  }
];

function search() {
  tableRef.value.getData(1);
}

function reset() {
  nextTick(() => {
    searchParams.value = {
      keywords: null,
      noticeState: null
    };
    search();
  });
}

const operateType = ref('add');
const modalVisible = ref(false);
const modleAddLoading = ref(false);
const currentRow = ref(null);
const addRef = ref(null);
function handleOpen(row) {
  currentRow.value = row;
  modalVisible.value = true;
  operateType.value = row ? 'edit' : 'add';
}

function handleClose() {
  modalVisible.value = false;
}
const recoverRef = ref(null);
async function handleOk() {
  const addObj = {
    ...addRef.value
  };
  await addObj.validateForm();

  modleAddLoading.value = true;
  let pro;
  const params = {
    ...addObj.model
  };
  if (operateType.value === 'add') {
    pro = addThroughHoleFrame(params);
  } else {
    pro = updateThroughHoleFrame({
      ...params,
      id: currentRow.value.id
    });
  }
  pro
    .then(({ error }) => {
      if (!error) {
        window.$message.success(`${operateType.value === 'add' ? '新增' : '修改'}成功`);
        handleClose();
        reset();
      }
    })
    .finally(() => (modleAddLoading.value = false));

  console.log(params);
}

function del(row) {
  window.$modal.confirm({
    title: `确定删除?`,
    onOk: () => {
      deleteThroughHoleFrame(row.id).then(({ error }) => {
        if (!error) {
          window.$message.success('删除成功');
          search();
        }
      });
    },
    onCancel: () => {}
  });
}

function exportExcel() {
  exportThroughHoleFrame({ ...searchParams.value });
}

const modalScrapVisible = ref(false);
const model = ref({
  repealRemark: null
});
const formList = [
  {
    type: 'textarea',
    key: 'reasonforscrapping',
    label: '报废原因',
    rule: {
      required: true,
      message: '请输入报废原因',
      trigger: 'blur'
    },
    placeholder: '请输入报废原因',
    span: 24
  }
];
const modleScrapLoading = ref(false);
const formRef = ref(null);
const currentScrap = ref(null);
function handleScrapOpen(row) {
  modalScrapVisible.value = true;
  currentScrap.value = row;
}

function handleScrapClose() {
  modalScrapVisible.value = false;
}

async function handleScrapOk() {
  const params = {
    ...model.value,
    id: currentScrap.value.id,
    states: '2'
  };
  await formRef.value.validateForm();
  modleScrapLoading.value = true;
  scrapThroughHoleFrame(params)
    .then(({ error }) => {
      if (!error) {
        window.$message.success('报废成功');
        handleScrapClose();
        reset();
      }
    })
    .finally(() => (modleScrapLoading.value = false));
}
</script>

<template>
  <div class="mold-maintenance-page min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <CommonSearch
      ref="commonSearchRef"
      v-model:searchParams="searchParams"
      :form-list="searchFormList"
      :is-search="true"
      @search="search"
      @reset="reset"
    ></CommonSearch>

    <Table
      ref="tableRef"
      v-model:searchParams="searchData"
      :column="column"
      :show-row-selection="false"
      row-key="id"
      :scroll="{ y: 'auto' }"
      is-init-get-data
      url="/qms/through/throughHoleFrame/selectAll"
    >
      <template #tableTitle>
        <AButton type="primary" class="mini-btn mr-8px" size="small" ghost @click="handleOpen(null)">
          <template #icon>
            <icon-ic-round-add class="align-sub text-icon" />
          </template>
          新增
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="exportExcel">
          <template #icon>
            <icon-ic-round-download class="align-sub text-icon" />
          </template>
          <span class="ml-3px">导出</span>
        </AButton>
      </template>
    </Table>
    <!-- 新增修改 -->
    <Modal
      v-model:visible="modalVisible"
      :title="`通孔架管理${operateType === 'add' ? '新增' : '修改'}`"
      width="700px"
      height="500px"
      :centered="true"
      :destroy-on-close="true"
      @close="handleClose"
    >
      <Add ref="addRef" :row-data="currentRow" :operate-type="operateType"></Add>
      <template #footer>
        <div class="modal-footer">
          <AButton :loading="modleAddLoading" type="primary" @click="handleOk">
            {{ operateType === 'add' ? '新增' : '修改' }}
          </AButton>
          <AButton @click="handleClose">关 闭</AButton>
        </div>
      </template>
    </Modal>

    <!-- 报废 -->

    <Modal
      v-model:visible="modalScrapVisible"
      title="报废"
      width="700px"
      height="232px"
      :centered="true"
      :destroy-on-close="true"
      @close="handleScrapClose"
    >
      <Form ref="formRef" v-model:model="model" :form-list="formList"></Form>
      <template #footer>
        <div class="modal-footer">
          <AButton :loading="modleScrapLoading" type="primary" @click="handleScrapOk">报废</AButton>
          <AButton @click="handleScrapClose">关 闭</AButton>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style lang="scss"></style>
